package cn.yunyichina.provider.pay.service.impl;

import static cn.yunyichina.provider.pay.service.impl.FinanceServiceImpl.YYYYMMDDHHMISS14;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.yunyichina.provider.framework.common.ResponseEnum;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.HisifaceService;
import cn.yunyichina.provider.framework.utils.UUIDUtil;
import cn.yunyichina.provider.iface.entity.base.LogVo;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.base.Rule;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.hisiface.finance.FinanceVo;
import cn.yunyichina.provider.iface.entity.hisiface.finance.FinanceVoResponse;
import cn.yunyichina.provider.pay.config.Config;
import cn.yunyichina.provider.pay.constant.PayEvent;
import cn.yunyichina.provider.pay.constant.ResponseFinance;
import cn.yunyichina.provider.pay.dao.HisOrderCheckedDao;
import cn.yunyichina.provider.pay.dao.HisOrderCheckedErrorDao;
import cn.yunyichina.provider.pay.dao.HisOrderDao;
import cn.yunyichina.provider.pay.dao.PaymentJournalDao;
import cn.yunyichina.provider.pay.entity.HisOrder;
import cn.yunyichina.provider.pay.entity.HisOrderChecked;
import cn.yunyichina.provider.pay.entity.HisOrderCheckedError;
import cn.yunyichina.provider.pay.entity.PaymentJournal;
import cn.yunyichina.provider.pay.service.HisPayfinanceService;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.convert.ObjectParser;


@Service
public class HisPayfinanceServiceImpl implements HisPayfinanceService {

	private static Logger logger = LoggerFactory.getLogger(HisPayfinanceServiceImpl.class);

	@Resource
	private HisOrderDao hisOrderDao;

	@Autowired
	private PaymentJournalDao paymentJournalDao;

	@Autowired
	private HisOrderCheckedDao hisOrderCheckedDao;

	@Autowired
	private HisOrderCheckedErrorDao hisOrderCheckedErrorDao;

	@Resource
	private FinanceServiceImpl financeService;


	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
	SimpleDateFormat sd = new SimpleDateFormat("HH:mm:ss");

	//region 重置对账数据
	/**
	 * @yyt.pay.his.payfinance.info.reset
	 * @param datas
	 * @return
	 */
	@Transactional(rollbackFor={Exception.class,ParseException.class})
	public Response resetHisPayfinanceInfo(String datas) throws ParseException,Exception {
		logger.info(datas);
		JSONObject maps = JsonUtils.parseObject(datas);
		String orgId = maps.getString("orgId");
		String beginPayTime = maps.getString("beginPayTime");//交易开始时间
		String endPayTime = maps.getString("endPayTime");//交易结束时间
		String isClearHis=maps.getString("isClearHis");//是否清除his流水记录，若为传值为“1”，则清除his流水记录，需重新拉取his账单。为“0”则不清除his流水记录。
		Response res=new Response();
		Date bdt = null;
		Date edt = null;
		try {
			if(StringUtils.isEmpty(orgId)){
				res.setResultCodeAndMessage(ResponseFinance.ORGID_EMPTY.getCode(),ResponseFinance.ORGID_EMPTY.getMessage());
				return  res;
			}else if(StringUtils.isEmpty(beginPayTime) || StringUtils.isEmpty(endPayTime)){
				res.setResultCodeAndMessage(ResponseFinance.PAYTIME_EMPTY.getCode(),ResponseFinance.PAYTIME_EMPTY.getMessage());
				return  res;
			}
			bdt = sdfDate.parse(beginPayTime);
			edt = sdfDate.parse(endPayTime);
			Calendar bRightNow = Calendar.getInstance();
			Calendar eRightNow = Calendar.getInstance();
			bRightNow.setTime(bdt);
			eRightNow.setTime(edt);
			bRightNow.add(Calendar.DAY_OF_YEAR, 1);
			eRightNow.add(Calendar.DAY_OF_YEAR, 1);
			String beginCheckTime=sdfDate.format(bRightNow.getTime()) + " 00:00:00";//对账开始时间
			String endCheckTime=sdfDate.format(eRightNow.getTime())  + " 23:59:59";//对账结束时间
			if("1".equals(isClearHis)){
				hisOrderDao.deleteByOrgIdAndPayTime(orgId,beginPayTime,endPayTime);//通过组织ID和交易开始、结束时间删除HIS流水数据
			}else if("0".equals(isClearHis)){
				hisOrderDao.updateByOrgIdAndPayTime(orgId,beginPayTime,endPayTime);//通过组织ID和交易开始、结束时间更新HIS流水数据
			}else{
				res.setResultCodeAndMessageAndResult(ResponseEnum.Common.FAILURE.getCode(), ResponseEnum.Common.FAILURE.getMessage(),"isClearHis is 1 or 0");
				return  res;
			}
			hisOrderCheckedErrorDao.deleteByOrgIdAndCheckTime(orgId,beginCheckTime,endCheckTime);//通过组织ID和第二次对账时间删除差错流水数据
			hisOrderCheckedDao.deleteByOrgIdAndCheckTime(orgId,beginCheckTime,endCheckTime);//通过组织ID和对账时间删除HIS已对平流水
		} catch (ParseException e){
			logger.error("ParseException", e);
			res.setResultCodeAndMessageAndResult(ResponseEnum.Common.FAILURE.getCode(), ResponseEnum.Common.FAILURE.getMessage(),e.toString());
			return  res;
		} catch (Exception ex){
			logger.error("Exception", ex);
			LogVo log = new LogVo();
			log.setOrgId(orgId);
			log.setEventCode(PayEvent.CK_CLEAN_HIS_DATA);
			log.setBatchNo(YYYYMMDDHHMISS14.format(new Date()));
			logger.info("resetHisPayfinanceInfo->insertLog request="
					+ JSON.toJSONString(log));
			FinanceServiceImpl.insertLog(orgId, "CK_CLEAN_HIS_DATA",ex.getMessage());
			throw  new Exception("Exception",ex);
			// res.setResultCodeAndMessageAndResult(ResponseEnum.Common.FAILURE.getMode(), ResponseEnum.Common.FAILURE.getMessage(),ex.toString());
		}
		return  res;
	}
	//endregion

	//region 获取his订单
	//yyt.pay.his.payfinance.info.get
	@Override
	public Response getHisPayfinanceInfo(String data) {
		long beginTime = new Date().getTime() / 1000;
		logger.info("<<<<< getHisPayfinanceInfo.beginTime:" + beginTime);
		Response res=new Response();
		List<HisOrder> hisOrderList=new ArrayList<HisOrder>();
		String orderMethod="yyt.base.order.by.orderno.get";
		Map<String,String> payFinanceMap = JsonUtils.parseObject(data, Map.class);
		Map<String,Object> platJourMap=new HashMap<String,Object>();//获取平台流水数据（交易日期内）
		List<PaymentJournal> payJournalList=new ArrayList<PaymentJournal>();//平台流水交易记录

		FinanceVo financeVo = new FinanceVo();
		financeVo.setBranchCode(payFinanceMap.get("branchCode"));
		financeVo.setHospitalCode(payFinanceMap.get("hospitalCode"));
		financeVo.setBeginPayDate(payFinanceMap.get("beginPayTime"));
		financeVo.setEndPayDate(payFinanceMap.get("endPayTime"));
		financeVo.setYytOrderNum(payFinanceMap.get("psOrdNum"));
		financeVo.setHisOrdNum(payFinanceMap.get("hisOrdNum"));
		financeVo.setPayMode(payFinanceMap.get("payMode"));
		financeVo.setPageNo(payFinanceMap.get("pageNo"));
		financeVo.setPageSize(payFinanceMap.get("pageSize"));
		try {
			logger.info("getHisPayfinanceInfo, yyt.pay.his.payfinance.info.get request="
					+ JSON.toJSONString(payFinanceMap));

			ResCommon<FinanceVoResponse> financeResponse=null;
			int pullCount=0;
			int pullMaxCount=5;
			while (pullCount<pullMaxCount){
				try{
					financeResponse= HisifaceService.getHisifaceClient().queryFinance(financeVo);
					if(financeResponse!=null&&"0".equals(financeResponse.getResultCode())){
						break;
					}
				}catch (Exception ex){
					logger.info("getHisPayfinanceInfo, yyt.pay.his.payfinance.info.get request=发生异常，当前拉取次数："+pullCount+"继续进行重试！");
				}
				pullCount++;
			}

			FinanceVoResponse finance=JsonUtils.parseObject(financeResponse.getResult(), FinanceVoResponse.class);
			logger.info("<<<<< getHisPayfinanceInfo.getHis.endTime:" + ((new Date().getTime() / 1000) - beginTime));
			if(finance!=null){
				if(finance.getFinances().size() < 1){
					res.setResultCodeAndMessage("0", "no datas");
					return res;
				}else{
					logger.info("getHisFinanceInfo->financeResponse=" + JSON.toJSONString(finance));

					PaymentJournal payJournal=new PaymentJournal();
					payJournal.setOrgId(payFinanceMap.get("orgId").toString());
					payJournal.setBeginPayTime( sdfDate.format(sdfDate.parse(payFinanceMap.get("beginPayTime"))) + " 00:00:00");
					payJournal.setEndPayTime( sdfDate.format(sdfDate.parse(payFinanceMap.get("beginPayTime"))) +" 23:59:59");
//	                		payJournal.setCheckStatus(Short.valueOf("1"));

					payJournalList=getPaymentJournalList(payJournal);

					if (null != payJournalList || payJournalList.size() > 0) {
						logger.info("getPaymentJournalList数据量:" +payJournalList.size());
						for(PaymentJournal payJou:payJournalList){
							platJourMap.put(payJou.getOrderNo(), payJou);
						}
					}

					String platformId=null;
					String platformName=null;
					String orgCode=null;
					String platformCode=null;
					String platformOrgAppName=null;
					String platformOrgAppCode=null;
					String payAppId=null;
					Integer accountAmount=null;//个账
					Integer medicareAmount=null;//统筹
					Integer insuranceAmount=null;//记账合计
					Integer totalAmount=null;
					PaymentJournal payJour=null;
					for (cn.yunyichina.provider.iface.entity.hisiface.finance.Finance financeinfo : finance.getFinances()) {

						accountAmount= StringUtils.isEmpty(financeinfo.getAccountAmount())?0: Integer.valueOf(new BigDecimal(financeinfo.getAccountAmount()).setScale(0, BigDecimal.ROUND_HALF_UP).intValue());
						medicareAmount=StringUtils.isEmpty(financeinfo.getMedicareAmount())?0:Integer.valueOf(new BigDecimal(financeinfo.getMedicareAmount()).setScale(0, BigDecimal.ROUND_HALF_UP).intValue());
						insuranceAmount=StringUtils.isEmpty(financeinfo.getInsuranceAmount())?0:Integer.valueOf(new BigDecimal(financeinfo.getInsuranceAmount()).setScale(0, BigDecimal.ROUND_HALF_UP).intValue());
						totalAmount=StringUtils.isEmpty(financeinfo.getTotalAmount())?0:Integer.valueOf(new BigDecimal(financeinfo.getTotalAmount()).setScale(0, BigDecimal.ROUND_HALF_UP).intValue());

						if(platJourMap.containsKey(financeinfo.getYytOrdNum())){
							payJour=(PaymentJournal)platJourMap.get(financeinfo.getYytOrdNum());
							platformId=payJour.getPlatformId();
							platformName=payJour.getPlatformName();
							orgCode=payJour.getOrgCode();
							platformCode=payJour.getPlatformCode();
							platformOrgAppName=payJour.getPlatformOrgAppName();
							platformOrgAppCode=payJour.getPlatformOrgAppCode();
							payAppId=payJour.getPayAppId();
						}else{
							//调用订单系统获取订单流水
							Map<String,String> getOrderNoMap=new HashMap<String,String>();
							getOrderNoMap.put("order_no", financeinfo.getYytOrdNum());
							logger.info("getHisPayfinanceInfo,yyt.base.order.by.orderno.get request="
									+financeinfo.getYytOrdNum());
							Response orderNoResponse = BaseService.callHumpFromInternal(orderMethod,
									JSON.toJSONString(getOrderNoMap));
							if("0".equals(orderNoResponse.getResultCode())){
								if(!StringUtils.isEmpty(orderNoResponse.getResult())){
									OrderExtVo order=JsonUtils.parseObject(orderNoResponse.getResult(), OrderExtVo.class);
									logger.info("getHisPayfinanceInfo,yyt.base.order.by.orderno.get reponse="
											+JSON.toJSONString(order));
									platformId=order.getPlatformId();
									platformName=order.getPlatformName();
									orgCode=order.getOrgCode();
									platformCode=order.getPlatformCode();
									platformOrgAppName=order.getPlatformOrgAppName();
									platformOrgAppCode=order.getPlatformOrgAppCode();
									payAppId=order.getPayAppId();
								}else{
									platformId=payFinanceMap.get("orgId");
									platformName=payFinanceMap.get("orgName");
								}
							}
						}

						HisOrder hisOrder=new HisOrder();
						hisOrder.setId(UUIDUtil.get32UUID());
						hisOrder.setOrgId(payFinanceMap.get("orgId").toString());
						hisOrder.setOrgName(payFinanceMap.get("orgName").toString());
						hisOrder.setPlatformId(platformId);
						hisOrder.setPlatformName(platformName);
						hisOrder.setPlatformCode(platformCode);
						hisOrder.setPlatformOrgAppName(platformOrgAppName);
						hisOrder.setPlatformOrgAppCode(platformOrgAppCode);
						hisOrder.setAccountAmount(accountAmount);
						hisOrder.setMedicareAmount(medicareAmount);
						hisOrder.setInsuranceAmount(insuranceAmount);
						hisOrder.setTotalAmount(totalAmount);
						hisOrder.setPayAppId(payAppId);
						hisOrder.setOrgCode(orgCode);
						hisOrder.setYytOrderNo(financeinfo.getYytOrdNum());
						hisOrder.setHisOrderNo(financeinfo.getHisOrdNum());
						hisOrder.setHisPaymentNo(financeinfo.getHisOrdJournalNum());
						hisOrder.setMedicalCardType(org.apache.commons.lang.StringUtils.isNotBlank(financeinfo.getPatCardType()) ? Short.valueOf(financeinfo.getPatCardType()) : null);
						hisOrder.setMedicalCardNo(financeinfo.getPatCardNo());
						hisOrder.setPatName(financeinfo.getPatName());
						hisOrder.setPaymentDealId(financeinfo.getAgtOrdNum());
						hisOrder.setOrderType(Short.valueOf(financeinfo.getOrderType()));
						hisOrder.setPayStatus(Short.valueOf(financeinfo.getPayStatus()));
						hisOrder.setCheckStatus((short)0);
						hisOrder.setPayAmount(Math.abs(ObjectParser.toInteger(financeinfo.getPayAmount())));
						hisOrder.setPayMode(Short.valueOf(financeinfo.getPayMode()));
						hisOrder.setPayTime(financeinfo.getPayTime());
						hisOrder.setCollectors(financeinfo.getCollectors());
						//hisOrder.setCheckTime("");
						hisOrder.setCreatedTime(sdf.format(new Date()));

						hisOrderList.add(hisOrder);
					}
				}
				if(hisOrderList.size() > 0 ){
					try {
						long batchInsertbeginTime = new Date().getTime() / 1000;
						logger.info("<<<<< getHisPayfinanceInfo.hisOrderDao.batchInsert.beginTime:" + batchInsertbeginTime);
						hisOrderDao.batchInsert(hisOrderList);
						logger.info("<<<<< getHisPayfinanceInfo.hisOrderDao.batchInsert批量入库消耗时间为:" + ((new Date().getTime() / 1000) - batchInsertbeginTime));
						res.setResultCodeAndMessageAndResult("0", "success","成功插入："+String.valueOf(hisOrderList.size()));
					} catch (Exception e) {
						logger.error("his流水批量插入数据库异常出错",e);
						e.printStackTrace();
						res.setResultCodeAndMessageAndResult("-1", "failure",e.toString());
						return res;
					}
				}

			}else{
				res.setResultCodeAndMessage(financeResponse.getResultCode(),payFinanceMap.get("beginPayTime") + financeResponse.getResultMessage());
			}


		} catch (Exception ex) {
			res.setResultCodeAndMessageAndResult("-1", "failure",ex.toString());
			logger.error("error", ex);
			LogVo log = new LogVo();
			log.setOrgId(payFinanceMap.get("orgId").toString());
			log.setOrgName(payFinanceMap.get("orgName").toString());
			log.setEventCode(PayEvent.CK_PULL_HIS_BILL);
			log.setBatchNo(YYYYMMDDHHMISS14.format(new Date()));
			log.setContent("Exception 获取his订单异常：" + ex.toString());
			logger.info("getHisPayfinanceInfo->insertLog request="
					+ JSON.toJSONString(log));
			FinanceServiceImpl.insertLog(payFinanceMap.get("orgId").toString(), "CK_PULL_HIS_BILL",ex.getMessage());
			return res;
		}
		logger.info("<<<<< getHisPayfinanceInfo.endTime:" + ((new Date().getTime() / 1000) - beginTime));
		return res;
	}
	//endregion

	//region 平台与HIS对账功能
	@SuppressWarnings("null")
	@Transactional(rollbackFor={Exception.class})
	public void checkHisPayFinancePlat(String datas) throws Exception {
		Map<String, String> maps = JsonUtils.parseObject(datas, Map.class);
		String orgId = maps.get("orgId");
		String payTime = maps.get("payTime");
		Date dt = null;
		boolean booleanCheckUsePaymentDealId=false;
		String orgCode=null;
		try {
			dt = sdfDate.parse(payTime);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Calendar rightNow = Calendar.getInstance();
		rightNow.setTime(dt);
		rightNow.add(Calendar.DAY_OF_YEAR, 1);
		String checkTime=sdfDate.format(rightNow.getTime())+" "+sd.format(new Date());
		Map<String,PaymentJournal> platJournNorMap=new HashMap<String,PaymentJournal>();//平台支付订单（支付、对账插入（支付））
		Map<String,HisOrder> hisOrderNorCompareMap=new HashMap<String,HisOrder>();//HIS方支付交易中平台流水号，待比较数据

		Map<String,PaymentJournal> platJournRefMap=new HashMap<String,PaymentJournal>();//平台支付订单（退款、对账插入（退款））
		Map<String,HisOrder> hisOrderRefCompareMap=new HashMap<String,HisOrder>();//HIS方退款交易中平台流水号，待比较数据

		List<PaymentJournal> payJournalList=new ArrayList<PaymentJournal>();//平台流水交易记录
		List<HisOrder> hisOrderList=new ArrayList<HisOrder>();//His流水交易记录


		//region  平台支付流水,包括正交易、退款交易
		PaymentJournal payJournal=new PaymentJournal();
		payJournal.setOrgId(orgId);
		payJournal.setBeginPayTime(payTime+" 00:00:00");
		payJournal.setEndPayTime(payTime + " 23:59:59");
		payJournal.setCheckStatus(Short.valueOf("1"));
		payJournal.setIsAutoRefund(Short.valueOf("0"));
		payJournalList=getPaymentJournalList(payJournal);
		if (null != payJournalList && payJournalList.size() > 0) {
			orgCode=payJournalList.get(0).getOrgCode();
			for(PaymentJournal payJou:payJournalList) {
				if ("1".equals(payJou.getPayStatus().toString()) || "4".equals(payJou.getPayStatus().toString())) {//正常
					platJournNorMap.put(payJou.getOrderNo(), payJou);
				} else if ("2".equals(payJou.getPayStatus().toString()) || "5".equals(payJou.getPayStatus().toString())) {//退款
					platJournRefMap.put(payJou.getOrderNo(), payJou);

				}
			}
		}
		//region 获取HIS交易流水，包括正常交易、退费交易
		HisOrder hisOrder=new HisOrder();
		hisOrder.setOrgId(orgId);
		hisOrder.setCheckStatus(Short.valueOf("0"));
		hisOrder.setBeginPayTime(payTime + " 00:00:00");
		hisOrder.setEndPayTime(payTime + " 23:59:59");
		hisOrderList=getHisOrder(hisOrder);
		if (null != hisOrderList && hisOrderList.size() > 0) {
			for(HisOrder hisOrd:hisOrderList) {
				if ("1".equals(hisOrd.getPayStatus().toString())) {//正常
					hisOrderNorCompareMap.put(hisOrd.getYytOrderNo(), hisOrd);
				} else if ("2".equals(hisOrd.getPayStatus().toString())) {//退费
					hisOrderRefCompareMap.put(hisOrd.getYytOrderNo(), hisOrd);
				}
			}
		}
		//endregion
		Map<String,String> ruleMap = new HashMap<String,String>();
		ruleMap.put("attribute_name" , Config.RULE_ATTRIBUTE_NAME_FOR_CHECKUSEPAYMENTDEALID);
		ruleMap.put("org_code" , orgCode);
		logger.info("请求selectRule方法，入参数为:"+JSON.toJSONString(ruleMap));
		Response ruleResp = BaseService.callHumpFromInternal("yyt.base.rule.select", JSON.toJSONString(ruleMap));
		logger.info("请求selectRule方法，出参数为:"+JSON.toJSONString(ruleResp));
		if("0".equals(ruleResp.getResultCode())){
			Rule rule=JsonUtils.parseObject(ruleResp.getResult(), Rule.class);
			if(!StringUtils.isEmpty(rule)){
				if("0".equals(rule.getAttributeProperties())){
					booleanCheckUsePaymentDealId=true;
				}
			}
		}
		logger.info("CheckUsePaymentDealId值为:"+booleanCheckUsePaymentDealId+",值为true不参与对账，flase则参与对账");
		//endregion
		logger.info("PlatNorDatas:"+JSON.toJSON(platJournNorMap));
		logger.info("HisNorDatas:"+JSON.toJSON(hisOrderNorCompareMap));
		logger.info("---------------------------------------------------");
		logger.info("PlatRefDatas:"+JSON.toJSON(platJournRefMap));
		logger.info("HisRefDatas:"+JSON.toJSON(hisOrderRefCompareMap));
		// region 正交易流水对账,1.以his订单为基准循环 2.循环平台，找出是否还有正常支付未对账的流水
		Iterator iterhisOrderNorCompare = hisOrderNorCompareMap.entrySet().iterator();
		String platPaymentDealId="";
		Integer platPayAmount=null;
		String hisPaymentDealId="";
		Integer hisPayAmount=null;
		String yytPayTime=null;
		while(iterhisOrderNorCompare.hasNext()){
			Map.Entry entryNorCompare = (Map.Entry) iterhisOrderNorCompare.next();
			if(entryNorCompare.getKey()==null){
				logger.info("His订单异常，无法识别订单号hisOrderNo：" + entryNorCompare.getValue());
				financeService.insertLog(orgId, "CK_CHECK_FAIL", "HIS与平台对账异常：" + "HIS那边返回的数据有问题，请校验His拉回来的订单，是否有平台订单号为空的情况!hisOrderNo：" + entryNorCompare.getValue());
				throw  new RuntimeException("HIS那边返回的数据有问题，请校验His拉回来的订单，是否有平台订单号为空的情况!hisOrderNo：" + entryNorCompare.getValue());
			}

			String hisNorCompareStr = entryNorCompare.getKey().toString();
			if(platJournNorMap.containsKey(hisNorCompareStr)) {//HIS方云医订单号存在平台
				Object plat = platJournNorMap.get(hisNorCompareStr);
				Object his = hisOrderNorCompareMap.get(hisNorCompareStr);
				if (plat instanceof PaymentJournal) {
					platPaymentDealId = ((PaymentJournal) plat).getPaymentDealId() == null ? "" : ((PaymentJournal) plat).getPaymentDealId().toString().trim();
					platPayAmount = ((PaymentJournal) plat).getPayAmount();
					yytPayTime = ((PaymentJournal) plat).getPayTime();
				}
				if (his instanceof HisOrder) {
					hisPaymentDealId = ((HisOrder) his).getPaymentDealId() == null ? "" : ((HisOrder) his).getPaymentDealId().toString().trim();
					hisPayAmount = ((HisOrder) his).getPayAmount();
				}
				boolean payAmontBoolean=!(hisPayAmount.toString().equals(platPayAmount.toString()));
				boolean paymentDealIdBoolean=booleanCheckUsePaymentDealId ? false : !(hisPaymentDealId.equals(platPaymentDealId));
				if (payAmontBoolean || paymentDealIdBoolean) {//金额不相等或者第三方支付交易流水号不相等、对账异常
					try {
						logger.info("支付->金额不相等或者第三方支付交易流水号不相等、对账异常判断部分,hisPayAmount:" + hisPayAmount +
								",platPayAmount:" + platPayAmount + ",hisPaymentDealId:" + hisPaymentDealId + ",platPaymentDealId:" + platPaymentDealId);
						PaymentJournal platJourn = (PaymentJournal) platJournNorMap.get(hisNorCompareStr);
						HisOrder ord = (HisOrder) hisOrderNorCompareMap.get(hisNorCompareStr);
						ord.setYytOrderNo(hisNorCompareStr);
						ord.setCheckStatus(Short.valueOf("4"));
						ord.setCheckTime(checkTime);
						hisOrderDao.update(ord);
						HisOrderCheckedError ordErr = new HisOrderCheckedError();
						ordErr.setId(UUIDUtil.get32UUID());
						ordErr.setOrgId(ord.getOrgId());
						ordErr.setOrgName(ord.getOrgName());
						ordErr.setOrgCode(ord.getOrgCode());
						ordErr.setPlatformId(ord.getPlatformId());
						ordErr.setPlatformName(ord.getPlatformName());
						ordErr.setPlatformOrgAppName(ord.getPlatformOrgAppName());
						ordErr.setPlatformOrgAppCode(ord.getPlatformOrgAppCode());
						ordErr.setPlatformCode(ord.getPlatformCode());
						ordErr.setPayAppId(ord.getPayAppId());
						ordErr.setYytOrderNo(ord.getYytOrderNo());
						ordErr.setHisOrderNo(ord.getHisOrderNo());
						ordErr.setHisPaymentNo(ord.getHisPaymentNo());
						ordErr.setMedicalCardType(ord.getMedicalCardType());
						ordErr.setMedicalCardNo(ord.getMedicalCardNo());
						ordErr.setPatName(ord.getPatName());
						ordErr.setPaymentDealId(ord.getPaymentDealId());
						ordErr.setOrderType(ord.getOrderType());
						ordErr.setPayStatus(ord.getPayStatus());
						ordErr.setHisPayAmount(hisPayAmount);
						ordErr.setHisAccountAmount(ord.getAccountAmount());
						ordErr.setHisMedicareAmount(ord.getMedicareAmount());
						ordErr.setHisInsuranceAmount(ord.getInsuranceAmount());
						ordErr.setHisTotalAmount(ord.getTotalAmount());
						ordErr.setYytAccountAmount(platJourn.getAccountAmount());
						ordErr.setYytMedicareAmount(platJourn.getMedicareAmount());
						ordErr.setYytInsuranceAmount(platJourn.getInsuranceAmount());
						ordErr.setYytTotalAmount(platJourn.getTotalAmount());
						ordErr.setYytPayAmount(platPayAmount);
						ordErr.setPayMode(ord.getPayMode());
						ordErr.setHisPayTime(ord.getPayTime());
						ordErr.setYytPayTime(yytPayTime);
						ordErr.setCheckStatus(Short.valueOf("4"));
						ordErr.setCreatedTime(sdf.format(new Date()));
						ordErr.setCollectors(ord.getCollectors());
						ordErr.setCheckTime(checkTime);
						if(payAmontBoolean){
							ordErr.setDescription("支付->对账异常判断部分,金额不相等,hisPayAmount:" + hisPayAmount +
									",platPayAmount:" + platPayAmount );
						}else{
							ordErr.setDescription("支付->对账异常判断部分,第三方支付交易流水号不相等 "+" hisPaymentDealId:"
									+hisPaymentDealId +",platPaymentDealId:" + platPaymentDealId );
						}
						hisOrderCheckedErrorDao.insert(ordErr);
						if (platJournNorMap.containsKey(hisNorCompareStr)) {
							platJournNorMap.remove(hisNorCompareStr);
						}
					} catch (Exception e) {
						logger.error("支付->金额不相等或第三方支付交易流水号插入数据库异常出错", e);
						e.printStackTrace();
						LogVo log = new LogVo();
						log.setOrgId(orgId);
						log.setEventCode("CK_PULL_HIS_BILL");
						log.setBatchNo(YYYYMMDDHHMISS14.format(new Date()));
						log.setContent("Exception 支付->金额不相等或第三方支付交易流水号插入数据库异常出错");
						logger.info("checkHisPayFinancePlat->insertLog request="
								+ JSON.toJSONString(log));
						FinanceServiceImpl.insertLog(orgId, "CK_PULL_HIS_BILL",e.getMessage());
						throw new Exception("支付->金额不相等或第三方支付交易流水号插入数据库异常出错",e);
					}
				} else {
					//当日对平
					try {
						logger.info("支付->当日对平判断部分,hisNorAndMoreStr:" + hisNorCompareStr);
						//更新HIS订单
						HisOrder ord = (HisOrder) hisOrderNorCompareMap.get(hisNorCompareStr);
						ord.setCheckStatus(Short.valueOf("1"));
						ord.setCheckTime(checkTime);
						hisOrderDao.update(ord);
						//新增HIS已对账流水
						HisOrderChecked hisCheck = new HisOrderChecked();
						hisCheck.setId(UUIDUtil.get32UUID());
						hisCheck.setOrgId(ord.getOrgId());
						hisCheck.setOrgName(ord.getOrgName());
						hisCheck.setOrgCode(ord.getOrgCode());
						hisCheck.setPlatformId(ord.getPlatformId());
						hisCheck.setPlatformName(ord.getPlatformName());
						hisCheck.setPlatformOrgAppName(ord.getPlatformOrgAppName());
						hisCheck.setPlatformOrgAppCode(ord.getPlatformOrgAppCode());
						hisCheck.setPlatformCode(ord.getPlatformCode());
						hisCheck.setPayAppId(ord.getPayAppId());
						hisCheck.setAccountAmount(ord.getAccountAmount());
						hisCheck.setMedicareAmount(ord.getMedicareAmount());
						hisCheck.setInsuranceAmount(ord.getInsuranceAmount());
						hisCheck.setTotalAmount(ord.getTotalAmount());
						hisCheck.setYytOrderNo(ord.getYytOrderNo());
						hisCheck.setHisOrderNo(ord.getHisOrderNo());
						hisCheck.setHisPaymentNo(ord.getHisPaymentNo());
						hisCheck.setMedicalCardType(ord.getMedicalCardType());
						hisCheck.setMedicalCardNo(ord.getMedicalCardNo());
						hisCheck.setPatName(ord.getPatName());
						hisCheck.setPaymentDealId(ord.getPaymentDealId());
						hisCheck.setOrderType(ord.getOrderType());
						hisCheck.setPayStatus(ord.getPayStatus());
						hisCheck.setCheckStatus(Short.valueOf("1"));
						hisCheck.setPayAmount(ord.getPayAmount());
						hisCheck.setPayMode(ord.getPayMode());
						hisCheck.setHisPayTime(ord.getPayTime());
						PaymentJournal payJo = (PaymentJournal) platJournNorMap.get(hisNorCompareStr);
						hisCheck.setYytPayTime(payJo.getPayTime());
						hisCheck.setCheckTime(checkTime);
						hisCheck.setCreatedTime(sdf.format(new Date()));
						hisCheck.setCollectors(ord.getCollectors());
						hisOrderCheckedDao.insert(hisCheck);
						//移除已对账的平台记录
						platJournNorMap.remove(hisNorCompareStr);
					} catch (Exception e) {
						logger.error("支付->当日对平数据异常出错", e);
						e.printStackTrace();
						LogVo log = new LogVo();
						log.setOrgId(orgId);
						log.setEventCode("CK_PULL_HIS_BILL");
						log.setBatchNo(YYYYMMDDHHMISS14.format(new Date()));
						log.setContent("Exception 支付->当日对平数据异常出错");
						logger.info("checkHisPayFinancePlat->insertLog request="
								+ JSON.toJSONString(log));
						FinanceServiceImpl.insertLog(orgId, "CK_PULL_HIS_BILL",e.getMessage());
						throw new Exception("支付->当日对平数据异常出错",e);
					}
				}
			}else {//不存在
				if (hisOrderNorCompareMap.containsKey(hisNorCompareStr)) {//当日存疑院方多
					//短款差错
					try {
						logger.info("支付->短款差错判断部分,hisNorAndMoreStr:" + hisNorCompareStr);
						HisOrder hisOrd = (HisOrder) hisOrderNorCompareMap.get(hisNorCompareStr);
						//插入HIS对账差错记录
						HisOrderCheckedError ordErr = new HisOrderCheckedError();

						ordErr.setId(UUIDUtil.get32UUID());
						ordErr.setOrgId(hisOrd.getOrgId());
						ordErr.setOrgName(hisOrd.getOrgName());
						ordErr.setOrgCode(hisOrd.getOrgCode());
						ordErr.setPlatformId(hisOrd.getPlatformId());
						ordErr.setPlatformName(hisOrd.getPlatformName());
						ordErr.setYytOrderNo(hisOrd.getYytOrderNo());
						ordErr.setHisOrderNo(hisOrd.getHisOrderNo());
						ordErr.setHisPaymentNo(hisOrd.getHisPaymentNo());
						ordErr.setMedicalCardType(hisOrd.getMedicalCardType());
						ordErr.setMedicalCardNo(hisOrd.getMedicalCardNo());
						ordErr.setPatName(hisOrd.getPatName());
						ordErr.setPaymentDealId(hisOrd.getPaymentDealId());
						ordErr.setOrderType(hisOrd.getOrderType());
						ordErr.setPayStatus(hisOrd.getPayStatus());
						ordErr.setHisPayAmount(hisOrd.getPayAmount());
						ordErr.setHisAccountAmount(hisOrd.getAccountAmount());
						ordErr.setHisMedicareAmount(hisOrd.getMedicareAmount());
						ordErr.setHisInsuranceAmount(hisOrd.getInsuranceAmount());
						ordErr.setHisTotalAmount(hisOrd.getTotalAmount());
						ordErr.setPlatformOrgAppName(hisOrd.getPlatformOrgAppName());
						ordErr.setPlatformOrgAppCode(hisOrd.getPlatformOrgAppCode());
						ordErr.setPlatformCode(hisOrd.getPlatformCode());
						ordErr.setPayAppId(hisOrd.getPayAppId());
						ordErr.setPayMode(hisOrd.getPayMode());
						ordErr.setHisPayTime(hisOrd.getPayTime());
						ordErr.setYytPayTime(hisOrd.getPayTime());  //暂时落hisPayTime
						ordErr.setCheckStatus(Short.valueOf("3"));
						ordErr.setCreatedTime(sdf.format(new Date()));
						ordErr.setCollectors(hisOrd.getCollectors());
						ordErr.setCheckTime(checkTime);
						hisOrderCheckedErrorDao.insert(ordErr);

						HisOrder ord = (HisOrder) hisOrderNorCompareMap.get(hisNorCompareStr);
						ord.setCheckStatus(Short.valueOf("3"));
						ord.setCheckTime(checkTime);
						hisOrderDao.update(ord);

					} catch (Exception e) {
						logger.error("支付->短款差错插入数据库异常出错", e);
						e.printStackTrace();
						LogVo log = new LogVo();
						log.setOrgId(orgId);
						log.setEventCode("CK_PULL_HIS_BILL");
						log.setBatchNo(YYYYMMDDHHMISS14.format(new Date()));
						log.setContent("Exception 支付->短款差错插入数据库异常出错");
						logger.info("checkHisPayFinancePlat->insertLog request="
								+ JSON.toJSONString(log));
						FinanceServiceImpl.insertLog(orgId, "CK_PULL_HIS_BILL",e.getMessage());
						throw new Exception("支付->短款差错插入数据库异常出错",e);
					}
				}
			}
		}

		//循环平台方（平台流水）是否有未对账的正常支付订单

		Iterator iteratorNor = platJournNorMap.keySet().iterator();
		while (iteratorNor.hasNext()) {
			String platKey = (String) iteratorNor.next();
			//长款差错
			try {
				logger.info("支付->当日存疑院方少长款差错判断部分,platKey:"+platKey);
				String payStatus="";
				//新增HIS对账存疑记录
				PaymentJournal ord=(PaymentJournal)platJournNorMap.get(platKey);
				HisOrderCheckedError ordErr=new HisOrderCheckedError();
				ordErr.setId(UUIDUtil.get32UUID());
				ordErr.setOrgId(ord.getOrgId());
				ordErr.setOrgName(ord.getOrgName());
				ordErr.setOrgCode(ord.getOrgCode());
				ordErr.setPlatformId(ord.getPlatformId());
				ordErr.setPlatformName(ord.getPlatformName());
				ordErr.setPlatformOrgAppName(ord.getPlatformOrgAppName());
				ordErr.setPlatformOrgAppCode(ord.getPlatformOrgAppCode());
				ordErr.setPlatformCode(ord.getPlatformCode());
				ordErr.setPayAppId(ord.getPayAppId());
				ordErr.setYytOrderNo(ord.getOrderNo());
				ordErr.setHisOrderNo(ord.getHisOrderNo());
				ordErr.setPaymentDealId(ord.getPaymentDealId());
				ordErr.setOrderType(ord.getOrderType());
				if("1".equals(ord.getPayStatus().toString())||"4".equals(ord.getPayStatus().toString())){
					payStatus="1";
				}else if("2".equals(ord.getPayStatus().toString())||"5".equals(ord.getPayStatus().toString())){
					payStatus="2";
				}
				ordErr.setPayStatus(Short.valueOf(payStatus));
				ordErr.setCheckStatus(Short.valueOf("2"));
				ordErr.setYytPayAmount(ord.getPayAmount());
				ordErr.setPayMode(ord.getPayMode());
				ordErr.setYytPayTime(ord.getPayTime());
				ordErr.setYytAccountAmount(ord.getAccountAmount());
				ordErr.setYytMedicareAmount(ord.getMedicareAmount());
				ordErr.setYytInsuranceAmount(ord.getInsuranceAmount());
				ordErr.setYytTotalAmount(ord.getTotalAmount());
				ordErr.setCreatedTime(sdf.format(new Date()));
				ordErr.setCheckTime(checkTime);
				hisOrderCheckedErrorDao.insert(ordErr);
			} catch (Exception e) {
				logger.error("支付->当日存疑院方少长款差错插入数据库异常出错",e);
				e.printStackTrace();
				LogVo log = new LogVo();
				log.setOrgId(orgId);
				log.setEventCode("CK_PULL_HIS_BILL");
				log.setBatchNo(YYYYMMDDHHMISS14.format(new Date()));
				log.setContent("Exception 支付->当日存疑院方少长款差错插入数据库异常出错");
				logger.info("checkHisPayFinancePlat->insertLog request="
						+ JSON.toJSONString(log));
				FinanceServiceImpl.insertLog(orgId, "CK_PULL_HIS_BILL",e.getMessage());
				// TODO: handle exception
				throw new Exception("支付->当日存疑院方少长款差错插入数据库异常出错",e);
			}
		}

		// endregion

		// region 退款交易流水对账,1.以his订单为基准循环 2.循环平台，找出是否还有退费支付未对账的流水
		Iterator iterhisOrderRefCompare = hisOrderRefCompareMap.entrySet().iterator();
		String platRefPaymentDealId=null;
		Integer platRefPayAmount=null;
		String hisRefPaymentDealId=null;
		Integer hisRefPayAmount=null;
		String yytRefPayTime=null;
		while(iterhisOrderRefCompare.hasNext()){
			Map.Entry entryRefCompare = (Map.Entry) iterhisOrderRefCompare.next();
			String hisRefCompareStr = entryRefCompare.getKey().toString();
			if(platJournRefMap.containsKey(hisRefCompareStr)){//HIS方云医退款订单号存在平台
				Object plat=platJournRefMap.get(hisRefCompareStr);
				Object his=hisOrderRefCompareMap.get(hisRefCompareStr);
				if(plat instanceof PaymentJournal){
					platRefPaymentDealId=((PaymentJournal)plat).getPaymentDealId();
					platRefPayAmount=((PaymentJournal)plat).getPayAmount();
					yytRefPayTime=((PaymentJournal)plat).getPayTime();
				}
				if(his instanceof HisOrder){
					hisRefPaymentDealId=((HisOrder)his).getPaymentDealId();
					hisRefPayAmount=((HisOrder)his).getPayAmount();
				}
				if(!(hisRefPayAmount.toString().equals(platRefPayAmount.toString()))){//金额不相等或者第三方支付交易流水号不相等、对账异常
					try {
						logger.info("退款->金额不相等对账异常判断部分,hisRefPayAmount:" + hisRefPayAmount +
								",platRefPayAmount:" + platRefPayAmount);
						//更新HIS流水表
						HisOrder ord = (HisOrder) hisOrderRefCompareMap.get(hisRefCompareStr);
						PaymentJournal platJourn = (PaymentJournal) platJournRefMap.get(hisRefCompareStr);
						ord.setYytOrderNo(hisRefCompareStr);
						ord.setCheckStatus(Short.valueOf("4"));
						ord.setCheckTime(checkTime);
						hisOrderDao.update(ord);
						//新增HIS对账差错记录
						HisOrderCheckedError ordErr = new HisOrderCheckedError();
						ordErr.setId(UUIDUtil.get32UUID());
						ordErr.setOrgId(ord.getOrgId());
						ordErr.setOrgName(ord.getOrgName());
						ordErr.setOrgCode(ord.getOrgCode());
						ordErr.setPlatformId(ord.getPlatformId());
						ordErr.setPlatformName(ord.getPlatformName());
						ordErr.setPlatformOrgAppName(ord.getPlatformOrgAppName());
						ordErr.setPlatformOrgAppCode(ord.getPlatformOrgAppCode());
						ordErr.setPlatformCode(ord.getPlatformCode());
						ordErr.setPayAppId(ord.getPayAppId());
						ordErr.setYytOrderNo(ord.getYytOrderNo());
						ordErr.setHisOrderNo(ord.getHisOrderNo());
						ordErr.setHisPaymentNo(ord.getHisPaymentNo());
						ordErr.setMedicalCardType(ord.getMedicalCardType());
						ordErr.setMedicalCardNo(ord.getMedicalCardNo());
						ordErr.setPatName(ord.getPatName());
						ordErr.setPaymentDealId(ord.getPaymentDealId());
						ordErr.setOrderType(ord.getOrderType());
						ordErr.setPayStatus(ord.getPayStatus());
						ordErr.setHisPayAmount(hisRefPayAmount);
						ordErr.setHisAccountAmount(ord.getAccountAmount());
						ordErr.setHisMedicareAmount(ord.getMedicareAmount());
						ordErr.setHisInsuranceAmount(ord.getInsuranceAmount());
						ordErr.setHisTotalAmount(ord.getTotalAmount());
						ordErr.setYytAccountAmount(platJourn.getAccountAmount());
						ordErr.setYytMedicareAmount(platJourn.getMedicareAmount());
						ordErr.setYytInsuranceAmount(platJourn.getInsuranceAmount());
						ordErr.setYytTotalAmount(platJourn.getTotalAmount());
						ordErr.setYytPayAmount(platRefPayAmount);
						ordErr.setPayMode(ord.getPayMode());
						ordErr.setHisPayTime(ord.getPayTime());
						ordErr.setYytPayTime(yytRefPayTime);
						ordErr.setCheckStatus(Short.valueOf("4"));
						ordErr.setCreatedTime(sdf.format(new Date()));
						ordErr.setCollectors(ord.getCollectors());
						ordErr.setCheckTime(checkTime);
						hisOrderCheckedErrorDao.insert(ordErr);
						if (platJournRefMap.containsKey(hisRefCompareStr)) {
							platJournRefMap.remove(hisRefCompareStr);
						}
					} catch (Exception e) {
						logger.error("退款->金额不相等或第三方支付交易流水号插入数据库异常出错", e);
						e.printStackTrace();
						LogVo log = new LogVo();
						log.setOrgId(orgId);
						log.setEventCode("CK_PULL_HIS_BILL");
						log.setBatchNo(YYYYMMDDHHMISS14.format(new Date()));
						log.setContent("Exception 退款->金额不相等或第三方支付交易流水号插入数据库异常出错");
						logger.info("checkHisPayFinancePlat->insertLog request="
								+ JSON.toJSONString(log));
						FinanceServiceImpl.insertLog(orgId, "CK_PULL_HIS_BILL",e.getMessage());
						throw new Exception("退款->金额不相等或第三方支付交易流水号插入数据库异常出错",e);
					}
				}else {
					//当日对平
					try {
						logger.info("退款->当日对平判断部分,hisNorAndMoreStr:" + hisRefCompareStr);
						//更新HIS订单
						HisOrder ord = (HisOrder) hisOrderRefCompareMap.get(hisRefCompareStr);
						ord.setCheckStatus(Short.valueOf("1"));
						ord.setCheckTime(checkTime);
						hisOrderDao.update(ord);
						//新增HIS已对账流水
						HisOrderChecked hisCheck = new HisOrderChecked();
						hisCheck.setId(UUIDUtil.get32UUID());
						hisCheck.setOrgId(ord.getOrgId());
						hisCheck.setOrgName(ord.getOrgName());
						hisCheck.setOrgCode(ord.getOrgCode());
						hisCheck.setPlatformId(ord.getPlatformId());
						hisCheck.setPlatformName(ord.getPlatformName());
						hisCheck.setPlatformOrgAppName(ord.getPlatformOrgAppName());
						hisCheck.setPlatformOrgAppCode(ord.getPlatformOrgAppCode());
						hisCheck.setPlatformCode(ord.getPlatformCode());
						hisCheck.setPayAppId(ord.getPayAppId());
						hisCheck.setAccountAmount(ord.getAccountAmount());
						hisCheck.setMedicareAmount(ord.getMedicareAmount());
						hisCheck.setInsuranceAmount(ord.getInsuranceAmount());
						hisCheck.setTotalAmount(ord.getTotalAmount());
						hisCheck.setYytOrderNo(ord.getYytOrderNo());
						hisCheck.setHisOrderNo(ord.getHisOrderNo());
						hisCheck.setHisPaymentNo(ord.getHisPaymentNo());
						hisCheck.setMedicalCardType(ord.getMedicalCardType());
						hisCheck.setMedicalCardNo(ord.getMedicalCardNo());
						hisCheck.setPatName(ord.getPatName());
						hisCheck.setPaymentDealId(ord.getPaymentDealId());
						hisCheck.setOrderType(ord.getOrderType());
						hisCheck.setPayStatus(ord.getPayStatus());
						hisCheck.setCheckStatus(Short.valueOf("1"));
						hisCheck.setPayAmount(ord.getPayAmount());
						hisCheck.setPayMode(ord.getPayMode());
						hisCheck.setHisPayTime(ord.getPayTime());
						PaymentJournal payJo = platJournRefMap.get(hisRefCompareStr);
						if (payJo != null) {
							hisCheck.setYytPayTime(payJo.getPayTime());
						}

						hisCheck.setCheckTime(checkTime);
						hisCheck.setCreatedTime(sdf.format(new Date()));
						hisCheck.setCollectors(ord.getCollectors());
						hisOrderCheckedDao.insert(hisCheck);
						//移除已对账的平台记录
						platJournRefMap.remove(hisRefCompareStr);
					} catch (Exception e) {
						logger.error("退款->当日对平数据异常出错", e);
						e.printStackTrace();
						LogVo log = new LogVo();
						log.setOrgId(orgId);
						log.setEventCode("CK_PULL_HIS_BILL");
						log.setBatchNo(YYYYMMDDHHMISS14.format(new Date()));
						log.setContent("Exception 退款->当日对平数据异常出错");
						logger.info("checkHisPayFinancePlat->insertLog request="
								+ JSON.toJSONString(log));
						FinanceServiceImpl.insertLog(orgId, "CK_PULL_HIS_BILL",e.getMessage());
						throw new Exception("退款->当日对平数据异常出错",e);
					}
				}
			}else{//不存在
				if(hisOrderRefCompareMap.containsKey(hisRefCompareStr)){//当日存疑院方多
					//长款差错
					try {
						logger.info("退款->长款差错判断部分,hisRefAndMoreStr:"+hisRefCompareStr);
						HisOrder ord=(HisOrder)hisOrderRefCompareMap.get(hisRefCompareStr);
						ord.setCheckStatus(Short.valueOf("2"));
						ord.setCheckTime(checkTime);
						hisOrderDao.update(ord);
						//插入HIS对账差错记录
						HisOrderCheckedError ordErr=new HisOrderCheckedError();
						ordErr.setId(UUIDUtil.get32UUID());
						ordErr.setOrgId(ord.getOrgId());
						ordErr.setOrgName(ord.getOrgName());
						ordErr.setOrgCode(ord.getOrgCode());
						ordErr.setPlatformId(ord.getPlatformId());
						ordErr.setPlatformName(ord.getPlatformName());
						ordErr.setPlatformOrgAppName(ord.getPlatformOrgAppName());
						ordErr.setPlatformOrgAppCode(ord.getPlatformOrgAppCode());
						ordErr.setPlatformCode(ord.getPlatformCode());
						ordErr.setPayAppId(ord.getPayAppId());
						ordErr.setYytOrderNo(ord.getYytOrderNo());
						ordErr.setHisOrderNo(ord.getHisOrderNo());
						ordErr.setHisPaymentNo(ord.getHisPaymentNo());
						ordErr.setMedicalCardType(ord.getMedicalCardType());
						ordErr.setMedicalCardNo(ord.getMedicalCardNo());
						ordErr.setPatName(ord.getPatName());
						ordErr.setPaymentDealId(ord.getPaymentDealId());
						ordErr.setOrderType(ord.getOrderType());
						ordErr.setPayStatus(ord.getPayStatus());
						ordErr.setHisPayAmount(ord.getPayAmount());
						ordErr.setPayMode(ord.getPayMode());
						ordErr.setYytPayTime(ord.getPayTime());  //暂时落hisPayTime
						ordErr.setHisPayTime(ord.getPayTime());
						ordErr.setCheckStatus(Short.valueOf("2"));
						ordErr.setCreatedTime(sdf.format(new Date()));
						ordErr.setCollectors(ord.getCollectors());
						ordErr.setCheckTime(checkTime);
						hisOrderCheckedErrorDao.insert(ordErr);
					} catch (Exception e) {
						logger.error("退款->长款差错插入数据库异常出错",e);
						e.printStackTrace();
						LogVo log = new LogVo();
						log.setOrgId(orgId);
						log.setEventCode("CK_PULL_HIS_BILL");
						log.setBatchNo(YYYYMMDDHHMISS14.format(new Date()));
						log.setContent("Exception 退款->长款差错插入数据库异常出错");
						logger.info("checkHisPayFinancePlat->insertLog request="
								+ JSON.toJSONString(log));
						FinanceServiceImpl.insertLog(orgId, "CK_PULL_HIS_BILL",e.getMessage());
						throw new Exception("退款->退款长款差错插入数据库异常出错",e);
					}
				}
			}
		}

		//循环平台方（平台流水）是否有未对账的退费支付订单

		Iterator iteratorRef = platJournRefMap.keySet().iterator();
		while (iteratorRef.hasNext()) {
			String platKey = (String) iteratorRef.next();
			//当日存疑院方少,短款差错
			try {
				logger.info("退款->当日存疑院方少判断部分,platKey:"+platKey);
				String payStatus="";
				//新增HIS对账存疑记录
				PaymentJournal ord=(PaymentJournal)platJournRefMap.get(platKey);
				//插入HIS对账差错记录
				HisOrderCheckedError ordErr=new HisOrderCheckedError();
				ordErr.setId(UUIDUtil.get32UUID());
				ordErr.setOrgId(ord.getOrgId());
				ordErr.setOrgName(ord.getOrgName());
				ordErr.setOrgCode(ord.getOrgCode());
				ordErr.setPlatformId(ord.getPlatformId());
				ordErr.setPlatformName(ord.getPlatformName());
				ordErr.setPlatformOrgAppName(ord.getPlatformOrgAppName());
				ordErr.setPlatformOrgAppCode(ord.getPlatformOrgAppCode());
				ordErr.setPlatformCode(ord.getPlatformCode());
				ordErr.setPayAppId(ord.getPayAppId());
				ordErr.setYytAccountAmount(ord.getAccountAmount());
				ordErr.setYytMedicareAmount(ord.getMedicareAmount());
				ordErr.setYytInsuranceAmount(ord.getInsuranceAmount());
				ordErr.setYytTotalAmount(ord.getTotalAmount());
				ordErr.setPlatformId(ord.getPlatformId());
				ordErr.setPlatformName(ord.getPlatformName());
				ordErr.setYytOrderNo(ord.getOrderNo());
				ordErr.setHisOrderNo(ord.getHisOrderNo());
				ordErr.setPaymentDealId(ord.getPaymentDealId());
				ordErr.setOrderType(ord.getOrderType());
				if("1".equals(ord.getPayStatus().toString())||"4".equals(ord.getPayStatus().toString())){
					payStatus="1";
				}else if("2".equals(ord.getPayStatus().toString())||"5".equals(ord.getPayStatus().toString())){
					payStatus="2";
				}
				ordErr.setPayStatus(Short.valueOf(payStatus));
//					ordErr.setHisPayAmount(ord.getPayAmount());
				ordErr.setYytPayAmount(ord.getPayAmount());
				ordErr.setPayMode(ord.getPayMode());
				ordErr.setYytPayTime(ord.getPayTime());
				ordErr.setCheckStatus(Short.valueOf("3"));
				ordErr.setCreatedTime(sdf.format(new Date()));
				ordErr.setCheckTime(checkTime);
				hisOrderCheckedErrorDao.insert(ordErr);
			} catch (Exception e) {
				logger.error("退款->当日存疑院方少转短款差错插入数据库异常出错",e);
				e.printStackTrace();
				LogVo log = new LogVo();
				log.setOrgId(orgId);
				log.setEventCode("CK_PULL_HIS_BILL");
				log.setBatchNo(YYYYMMDDHHMISS14.format(new Date()));
				log.setContent("Exception 退款->当日存疑院方少转短款差错插入数据库异常出错");
				logger.info("checkHisPayFinancePlat->insertLog request="
						+ JSON.toJSONString(log));
				FinanceServiceImpl.insertLog(orgId, "CK_PULL_HIS_BILL",e.getMessage());
				// TODO: handle exception
				throw new Exception("退款->当日存疑院方少转短款差错插入数据库异常出错",e);
			}
//				LogVo log = new LogVo();
//				log.setOrgId(orgId);
//				log.setEventCode(PayEvent.CK_CHECK_SUCESSFUL);
//				log.setBatchNo(YYYYMMDDHHMISS14.format(new Date()));
//				logger.info("checkHisPayFinancePlat->insertLog request="
//						+ JSON.toJSONString(log));
//				FinanceServiceImpl.insertLog(orgId, PayEvent.CK_CHECK_SUCESSFUL,"成功");
		}
		// endregion

	}

	//endregion	

	//region 根据条件筛选平台支付流水
	/**
	 * 根据条件筛选平台支付流水
	 * @param payJournal
	 * @return
	 */
	@SuppressWarnings("null")
	public List<PaymentJournal> getPaymentJournalList(PaymentJournal payJournal){

		List<PaymentJournal> payJournalList=new ArrayList<PaymentJournal>();
		try {
			payJournalList=paymentJournalDao.select(payJournal);
			if (null != payJournalList || payJournalList.size() > 0) {
				return payJournalList;
			}else{
				payJournalList=new ArrayList<PaymentJournal>();
			}
		} catch (Exception e) {
			logger.error("getPaymentJournalList",e);
			e.printStackTrace();
		}
		return payJournalList;
	}
	//endregion

	//region 根据条件筛选HIS方支付流水
	/**
	 * 根据条件筛选HIS方支付流水
	 * @param hisOrder
	 * @return
	 */
	@SuppressWarnings("null")
	public List<HisOrder> getHisOrder(HisOrder hisOrder){

		List<HisOrder> hisOrderList=new ArrayList<HisOrder>();
		try {
			hisOrderList=hisOrderDao.select(hisOrder);
			if (null != hisOrderList || hisOrderList.size() > 0) {
				return hisOrderList;
			}else{
				hisOrderList=new ArrayList<HisOrder>();
			}
		} catch (Exception e) {
			logger.error("getHisOrder",e);
			e.printStackTrace();
		}
		return hisOrderList;
	}
	//endregion
}
